<?php declare(strict_types=1);


namespace App\Model\Logic;

use Swoft\Db\DB;
use Swoft\Db\Exception\DbException;

use App\Model\Entity\Tags;

use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
use Thepixeldeveloper\Sitemap\Sitemap as TMap;

class SiteMap
{
    private static $link;

    /**
     * @param string $sitemap
     * @param string $link
     * @return bool|int
     */
    public static function make(string $sitemap, string $link)
    {
        $urlset = new Urlset();
        $mobile = new Mobile();
        $mobile->setType('pc,mobile');

        $tags = Tags::orderby('sortorder', 'asc')->pluck('id');
        foreach ($tags as $id => $tag) {
            $url = new Url($link . '/tag/' . $tag);
            $url->addExtension($mobile);
            $url->setPriority('1.0');
            $urlset->add($url);
        }
        $driver = new XmlWriterDriver();
        $driver->addProcessingInstructions('urlset', 'xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/');
        $urlset->accept($driver);
        $map = $driver->output();
        return file_put_contents($sitemap, $map);
    }

    /**
     * @param string $link
     * @param string $base_path
     * @throws DbException
     * @throws \Exception
     */
    public static function sitemapIndex(string $link, string $base_path)
    {
        self::$link = $link;
        $path       = $base_path . 'sitemap';
        if (!is_dir($path) && !mkdir($path)) {
            throw new \Exception('没有创建目录权限!');
        }
        $path    .= DIRECTORY_SEPARATOR . 'map_';
        $count   = 0;
        $update  = [];
        $tempArr = [];
        for ($i = 1; $i <= config('max_table_no'); $i++) {
            $table     = 'question' . str_pad((string)$i, 3, '0', STR_PAD_LEFT);
            $questions = DB::table($table)->pluck('question_id')->toArray();
            if (count($questions) > 9990) {
                $tempArr = array_merge($tempArr, array_splice($questions, 9990));
                array_push($update, self::subSitemap($questions, $path, $count));
                while (count($tempArr) > 9990) {
                    $temp = array_splice($tempArr, 0, 9990);
                    array_push($update, self::subSitemap($temp, $path, $count));
                }
            } else {
                array_push($update, self::subSitemap($questions, $path, $count));
            }
        }

        if (count($tempArr)) {
            array_push($update, self::subSitemap($tempArr, $path, $count));
        }

        if (array_sum($update)) {
            //索引 siteMap
            $sitemapindex = $base_path . 'sitemapindex.xml';
            $indexUrlset  = new SitemapIndex;
            for ($j = 1; $j <= $count; $j++) {
                $siteMap = $path . $j . '.xml';
                $date    = date('Y-m-d', filemtime($siteMap));
                $url     = new TMap($link . '/sitemap/map_' . $j . '.xml');
                $url->setLastMod($date);
                $indexUrlset->add($url);
            }

            $driver = new XmlWriterDriver;
            $indexUrlset->accept($driver);
            file_put_contents($sitemapindex, $driver->output());
        }
    }

    /**
     * @param array $question_id
     * @param string $path
     * @param int $count
     */
    private static function subSitemap(array $question_id, string $path, int &$count): bool
    {
        $count++;
        $fileName = $path . $count . '.xml';
        if (is_file($fileName)) {
            return false;
        }
        $urlset = new Urlset();
        $mobile = new Mobile();
        $mobile->setType('pc,mobile');

        foreach ($question_id as $index => $id) {
            $url = new Url(self::$link . '/a/' . $id);
            $url->addExtension($mobile);
            $url->setPriority('0.9');
            $urlset->add($url);
        }

        $driver = new XmlWriterDriver;
        $driver->addProcessingInstructions('urlset', 'xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/');
        $urlset->accept($driver);
        $map = $driver->output();
        if ($flag = file_put_contents($fileName, $map)) {
            return true;
        }
        return false;
    }
}
